﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;

using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;

namespace autoIncrement
{
    public class increment : IPlugin
    {
        public void Execute(IPluginExecutionContext context)
        {
			// Verify we have an entity to work with
            try
            {
                if (context.InputParameters.Properties.Contains("Target") && context.InputParameters.Properties["Target"] is DynamicEntity)
                {

                    //create service object
                    ICrmService service = context.CreateCrmService(false);

                    //get entity settings from autoincrement entity
                    ColumnSet col = new ColumnSet(new string[] { "new_appendatend", "new_appendatstart", "new_incrementby", "new_lastid", "new_maxvalue", "new_name" });

                    ConditionExpression con = new ConditionExpression("new_name", ConditionOperator.Equal, new object[] { context.PrimaryEntityName });

                    FilterExpression fil = new FilterExpression();
                    fil.FilterOperator = LogicalOperator.And;
                    fil.Conditions.Add(con);

                    QueryExpression query = new QueryExpression("new_autoincrementid");
                    query.ColumnSet = col;
                    query.Criteria = fil;
                    query.EntityName = "new_autoincrement";

                    DynamicEntity autoincrement = (DynamicEntity)service.RetrieveMultiple(query).BusinessEntities[0];

                    //generate autoincrementid
                    StringBuilder autoIncId = new StringBuilder();
                    autoIncId.Append(autoincrement["new_appendatstart"].ToString());

                    int num = int.Parse(autoincrement["new_lastid"].ToString());
                    num += int.Parse(autoincrement["new_incrementby"].ToString());

                    autoIncId.Append(num);
                    autoIncId.Append(autoincrement["new_appendatend"].ToString());

                    //update the record with autoincrement value
                    DynamicEntity thisEntity = (DynamicEntity)context.InputParameters.Properties["Target"];

                    if (thisEntity.Properties.Contains("new_autoincfield"))
                    {
                        thisEntity.Properties["new_autoincfield"] = autoIncId.ToString();
                    }
                    else
                    {
                        StringProperty autoIncFieldPro = new StringProperty("new_autoincfield", autoIncId.ToString());
                        thisEntity.Properties.Add(autoIncFieldPro);
                    }

                    service.Update(thisEntity);

                    //update autoincrement entity with latest value
                    CrmNumberProperty crmNumPro = new CrmNumberProperty();
                    crmNumPro.Name = "new_lastid";
                    crmNumPro.Value = new CrmNumber();
                    crmNumPro.Value.Value = num;

                    autoincrement["new_lastid"] = crmNumPro;

                    service.Update(autoincrement);
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
    }
}
